import React, { useState, useEffect } from 'react';
import { 
  IonPage, 
  IonContent, 
  IonHeader, 
  IonToolbar, 
  IonButtons, 
  IonMenuButton, 
  IonTitle,
  IonSearchbar,
  IonSegment,
  IonSegmentButton,
  IonList,
  IonItem,
  IonThumbnail,
  IonLabel,
  IonNote,
  IonBadge,
  IonButton,
  IonIcon,
  IonFab,
  IonFabButton,
  IonGrid,
  IonRow,
  IonCol,
  useIonViewWillEnter
} from '@ionic/react';
import { 
  heart, 
  heartOutline, 
  star, 
  starOutline, 
  bookmark, 
  bookmarkOutline,
  search,
  add,
  trash,
  shareSocial,
  ellipsisHorizontal,
  time,
  folder,
  list
} from 'ionicons/icons';
import './FavoritesPage.css';

// 收藏项类型定义
type FavoriteType = 'all' | 'articles' | 'products' | 'places' | 'notes';

interface FavoriteItem {
  id: string;
  title: string;
  description: string;
  image: string;
  type: FavoriteType;
  tags: string[];
  date: string;
  rating: number;
  isFavorite: boolean;
}

const FavoritesPage: React.FC = () => {
  const [searchText, setSearchText] = useState('');
  const [selectedType, setSelectedType] = useState<FavoriteType>('all');
  const [favorites, setFavorites] = useState<FavoriteItem[]>([]);
  const [filteredFavorites, setFilteredFavorites] = useState<FavoriteItem[]>([]);
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [allTags, setAllTags] = useState<string[]>([]);

  // 模拟加载收藏数据
  const loadFavorites = () => {
    const mockFavorites: FavoriteItem[] = [
      {
        id: '1',
        title: 'React 最佳实践指南',
        description: '关于React开发的最佳实践和性能优化技巧',
        image: 'https://picsum.photos/200/200?random=1',
        type: 'articles',
        tags: ['前端', 'React', 'JavaScript'],
        date: '2023-06-15',
        rating: 4.5,
        isFavorite: true
      },
      {
        id: '2',
        title: 'Ionic 框架入门',
        description: '使用Ionic构建跨平台应用的完整指南',
        image: 'https://picsum.photos/200/200?random=2',
        type: 'articles',
        tags: ['移动开发', 'Ionic', '教程'],
        date: '2023-07-20',
        rating: 4.8,
        isFavorite: true
      },
      {
        id: '3',
        title: '无线蓝牙耳机',
        description: '高品质音效，长续航蓝牙耳机',
        image: 'https://picsum.photos/200/200?random=3',
        type: 'products',
        tags: ['电子产品', '耳机', '蓝牙'],
        date: '2023-08-10',
        rating: 4.3,
        isFavorite: true
      },
      {
        id: '4',
        title: '中央公园咖啡厅',
        description: '纽约最好的咖啡体验，舒适的环境',
        image: 'https://picsum.photos/200/200?random=4',
        type: 'places',
        tags: ['咖啡', '休闲', '纽约'],
        date: '2023-09-05',
        rating: 4.7,
        isFavorite: true
      },
      {
        id: '5',
        title: '项目会议纪要',
        description: '2023年Q4项目规划会议记录',
        image: 'https://picsum.photos/200/200?random=5',
        type: 'notes',
        tags: ['工作', '会议', '项目'],
        date: '2023-10-12',
        rating: 4.0,
        isFavorite: true
      },
      {
        id: '6',
        title: 'JavaScript设计模式',
        description: 'JavaScript中常用的设计模式实现',
        image: 'https://picsum.photos/200/200?random=6',
        type: 'articles',
        tags: ['JavaScript', '设计模式', '编程'],
        date: '2023-11-01',
        rating: 4.6,
        isFavorite: true
      },
      {
        id: '7',
        title: '智能手表',
        description: '多功能健康监测智能手表',
        image: 'https://picsum.photos/200/200?random=7',
        type: 'products',
        tags: ['可穿戴', '健康', '智能设备'],
        date: '2023-11-15',
        rating: 4.4,
        isFavorite: true
      }
    ];
    
    setFavorites(mockFavorites);
    
    // 提取所有标签
    const tags = Array.from(new Set(mockFavorites.flatMap(item => item.tags)));
    setAllTags(tags);
  };

  // 页面加载时获取收藏数据
  useIonViewWillEnter(() => {
    loadFavorites();
  });

  // 筛选收藏项
  useEffect(() => {
    let filtered = favorites;
    
    // 按类型筛选
    if (selectedType !== 'all') {
      filtered = filtered.filter(item => item.type === selectedType);
    }
    
    // 按搜索文本筛选
    if (searchText) {
      const searchLower = searchText.toLowerCase();
      filtered = filtered.filter(
        item => 
          item.title.toLowerCase().includes(searchLower) || 
          item.description.toLowerCase().includes(searchLower) ||
          item.tags.some(tag => tag.toLowerCase().includes(searchLower))
      );
    }
    
    // 按标签筛选
    if (selectedTags.length > 0) {
      filtered = filtered.filter(item => 
        selectedTags.every(tag => item.tags.includes(tag))
      );
    }
    
    setFilteredFavorites(filtered);
  }, [favorites, selectedType, searchText, selectedTags]);

  // 切换收藏状态
  const toggleFavorite = (id: string) => {
    setFavorites(favorites.map(item => 
      item.id === id ? { ...item, isFavorite: !item.isFavorite } : item
    ));
  };

  // 切换标签选择
  const toggleTag = (tag: string) => {
    if (selectedTags.includes(tag)) {
      setSelectedTags(selectedTags.filter(t => t !== tag));
    } else {
      setSelectedTags([...selectedTags, tag]);
    }
  };

  // 清空所有筛选
  const clearFilters = () => {
    setSearchText('');
    setSelectedType('all');
    setSelectedTags([]);
  };

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonButtons slot="start">
            <IonMenuButton />
          </IonButtons>
          
          <IonTitle>我的收藏</IonTitle>
          
          <IonButtons slot="end">
            <IonButton>
              <IonIcon slot="icon-only" icon={ellipsisHorizontal} />
            </IonButton>
          </IonButtons>
        </IonToolbar>
        
        {/* 搜索栏 */}
        <IonToolbar>
          <IonSearchbar 
            placeholder="搜索收藏内容" 
            value={searchText}
            onIonChange={e => setSearchText(e.detail.value!)}
            animated
          />
        </IonToolbar>
        
        {/* 分类筛选 */}
        <IonToolbar>
          <IonSegment 
            value={selectedType} 
            onIonChange={e => setSelectedType(e.detail.value as FavoriteType)}
            scrollable
          >
            <IonSegmentButton value="all">
              <IonIcon icon={list} />
              <IonLabel>全部</IonLabel>
            </IonSegmentButton>
            <IonSegmentButton value="articles">
              <IonIcon icon={bookmark} />
              <IonLabel>文章</IonLabel>
            </IonSegmentButton>
            <IonSegmentButton value="products">
              <IonIcon icon={star} />
              <IonLabel>产品</IonLabel>
            </IonSegmentButton>
            <IonSegmentButton value="places">
              <IonIcon icon={folder} />
              <IonLabel>地点</IonLabel>
            </IonSegmentButton>
            <IonSegmentButton value="notes">
              <IonIcon icon={time} />
              <IonLabel>笔记</IonLabel>
            </IonSegmentButton>
          </IonSegment>
        </IonToolbar>
      </IonHeader>
      
      <IonContent className="ion-padding">
        {/* 标签筛选 */}
        {allTags.length > 0 && (
          <div className="tags-container">
            <IonLabel className="tags-label">标签筛选:</IonLabel>
            <div className="tags-list">
              {allTags.map(tag => (
                <IonButton 
                  key={tag}
                  size="small"
                  fill={selectedTags.includes(tag) ? "solid" : "outline"}
                  color={selectedTags.includes(tag) ? "primary" : "medium"}
                  onClick={() => toggleTag(tag)}
                >
                  {tag}
                </IonButton>
              ))}
            </div>
          </div>
        )}
        
        {/* 筛选状态提示 */}
        {(searchText || selectedType !== 'all' || selectedTags.length > 0) && (
          <div className="filter-status">
            <IonNote>
              当前筛选: 
              {selectedType !== 'all' && ` 类型: ${selectedType}`}
              {searchText && ` 搜索: "${searchText}"`}
              {selectedTags.length > 0 && ` 标签: ${selectedTags.join(', ')}`}
            </IonNote>
            <IonButton 
              size="small" 
              fill="clear" 
              color="medium"
              onClick={clearFilters}
            >
              清除筛选
            </IonButton>
          </div>
        )}
        
        {/* 收藏列表 */}
        {filteredFavorites.length > 0 ? (
          <IonList lines="full" className="favorites-list">
            {filteredFavorites.map(item => (
              <IonItem key={item.id} className="favorite-item">
                <IonThumbnail slot="start">
                  <img src={item.image} alt={item.title} />
                </IonThumbnail>
                
                <IonLabel>
                  <h2>{item.title}</h2>
                  <p>{item.description}</p>
                  <div className="item-meta">
                    <IonNote>
                      <IonIcon icon={time} size="small" />
                      {item.date}
                    </IonNote>
                    <div className="item-tags">
                      {item.tags.map(tag => (
                        <IonBadge 
                          key={tag} 
                          color="medium"
                          className="tag-badge"
                        >
                          {tag}
                        </IonBadge>
                      ))}
                    </div>
                  </div>
                </IonLabel>
                
                <div slot="end" className="item-actions">
                  <IonButton 
                    fill="clear" 
                    color={item.isFavorite ? "danger" : "medium"}
                    onClick={() => toggleFavorite(item.id)}
                  >
                    <IonIcon 
                      icon={item.isFavorite ? heart : heartOutline} 
                      slot="icon-only" 
                    />
                  </IonButton>
                  
                  <IonButton fill="clear" color="medium">
                    <IonIcon icon={shareSocial} slot="icon-only" />
                  </IonButton>
                </div>
              </IonItem>
            ))}
          </IonList>
        ) : (
          <div className="empty-state">
            <IonIcon icon={bookmarkOutline} size="large" color="medium" />
            <h3>没有收藏内容</h3>
            <p>您还没有收藏任何内容</p>
            <IonButton fill="outline" onClick={clearFilters}>
              查看所有收藏
            </IonButton>
          </div>
        )}
        
        {/* 添加收藏按钮 */}
        <IonFab vertical="bottom" horizontal="end" slot="fixed">
          <IonFabButton color="primary">
            <IonIcon icon={add} />
          </IonFabButton>
        </IonFab>
      </IonContent>
    </IonPage>
  );
};

export default FavoritesPage;